import { ref } from 'vue'
import is from '@/utils/is'
import { adapter, request } from '@/request'
import { sdKeywordListByGet } from '@/core/api/priceSheet'
import { message } from 'ant-design-vue'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import { PlatformEnum, ProductEnum } from '@/core/enums/platform'
import type { RequestWrapper } from '@/core/interfaces/common'
import type { ComboPricePack } from '@/core/interfaces/combo'
import { object } from 'zod'

export interface sdPriceAskParams {
  cibao: ProductEnum
  keyword: string | string[]
  comboPriceId?: ComboPricePack['comboPriceId']
  packageId?: number
  productId?: number
  zzbwOrderNo?: string
  serviceAreas?: string[]
}

export default function getKeywordList() {
  const service = adapter<
    RequestWrapper<{
      wordPV: PriceKeyword[]
      heatWords: PriceKeyword[]
    }>
  >(request)
  const loading = ref(false)
  const response = ref<PriceKeyword[]>([])

  const fetch = (data: Pick<sdPriceAskParams, 'keyword'>) => {
    const { url, method } = sdKeywordListByGet()

    loading.value = true
    const item = data.keyword
      .toLowerCase()
      .split(/[\n\r\s,，;；]+/g)
      .filter((t) => t !== '')

    return service({
      config: {
        url,
        method,
        data: {
          keywords: item,
          productId: data.productId,
          comboId: data.comboId,
          serviceAreas: data.serviceAreas
        }
      },
      callback: (res) => {},

      callback: (res) => {
        function formatter(item: PriceKeyword) {
          const productId = localStorage.getItem('productId')

          return {
            ...item,
            frontKey: `${item.name}|-|${item.clientType}`,
            selected: false,
            reasons: item.showReasons ? item.showReasons.split(',') : [],
            loading: false
          }
        }

        const wordPV = res.data.data.wordPV.map(formatter)
        const heatWords = res.data.data.heatWords.map(formatter)

        response.value = wordPV.concat(heatWords)
      },
      error: (err) => {
        if (is.error(err)) {
          message.error(err.message)
        }
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
